<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller\Backend;

use App\Constants\ErrorCode;
use App\Constants\SuccessCode;
use App\Exception\BusinessException;
use App\Model\Admin;
use App\Model\NoticeGlobal;
use App\Models\Menu;
use App\Resource\Backend\AdminResource;
use App\Resource\BaseResource;
use App\Traits\PwdTool;
use Carbon\Carbon;
use App\Controller\AbstractController;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\View\RenderInterface;

class Auth extends AbstractController
{
    use PwdTool;

    /*
     * login
     */
    public function login(RequestInterface $request, ResponseInterface $response)
    {
        $login_name = $request->input('username');
        $passwd = $request->input('passwd');

        $admin = Admin::where('login_name', $login_name)->first();
        if (! $admin) {
            throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'User does not exist');
        }

        $admin->last_login_ip = get_client_ip();
        $admin->last_login_at = Carbon::now()->toDateTimeString();
        $admin->user_agent = ! empty($header) ? $header[0] : '';
        $admin->save();

        if ($this->verifyPassword($passwd, $admin->password)) {
            $this->session->set('admin_user', $admin);
            return new AdminResource($admin);
        }

         throw new BusinessException(ErrorCode::AUTH_USER_NO_HAVA_ERROR);
    }

    public function logout(RequestInterface $request)
    {
        $this->session->remove('admin_user');
        return new BaseResource();
    }

    public function getUser(RequestInterface $request)
    {
        $admin = Admin::find($this->session->get('admin_user')->id);

        return new AdminResource($admin);
    }

    public function setUser(RequestInterface $request)
    {

        $admin = Admin::find($this->session->get('admin_user')->id);
        if ($request->input('user_name')) {

            $admin->user_name = $request->input('user_name');
        }
        if ($request->input('avatar')) {

            $admin->avatar = $request->input('avatar');
        }
        if ($request->input('password')) {

            $admin->user_name = $this->makePassword( $request->input('password') );
        }

        $admin->save();
        return new BaseResource();
    }

    public function manage(RenderInterface $render)
    {
        return $render->render('manage');
    }

    public function front(RenderInterface $render)
    {
        return $render->render('front');
    }

    public function loginSuccess(RenderInterface $render)
    {
        return $render->render('loginSuccess');
    }
}
